package page

import (
	"io"
	"os"
	"path/filepath"

	"gitee.com/haodreams/golib/easyroute/group"
	"gitee.com/haodreams/golib/estring"
	"github.com/gin-gonic/gin"
)

type FileController struct {
	group.Group
}

func (m *FileController) Upload(c *gin.Context) {
	if m.IsPost(c) {
		header, err := c.FormFile("file")
		if err != nil {
			c.JSON(200, map[string]any{"code": 412, "msg": err.Error()})
			return
		}
		dst := header.Filename
		fileName := filepath.Base(dst)
		f, err := header.Open()
		if err != nil {
			c.JSON(200, map[string]any{"code": 500, "msg": err.Error()})
			return
		}

		defer f.Close()

		if _, err := os.Stat("temp"); err != nil {
			os.MkdirAll("temp", 0755)
		}

		lf, err := os.Create("temp/" + fileName)
		if err != nil {
			c.JSON(200, map[string]any{"code": 500, "msg": err.Error()})
			return
		}

		defer lf.Close()

		size, _ := io.Copy(lf, f)
		msg := estring.FormatSize(size)
		c.JSON(200, map[string]any{"code": 200, "msg": "上传成功， 上传大小:" + msg})
		return
	}
	html := `<!DOCTYPE html>
		<html> <head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>upload file</title>
		</head><body><form action="/sys/file/upload" method="post" enctype="multipart/form-data">
		<input type="file" name="file" value="" /> 	<input type="submit" name="submit" />
		</form> </body></html>
		`
	c.Writer.Header().Add("Content-Type", "text/html")
	c.Writer.WriteHeader(200)
	c.Writer.Write([]byte(html))
}
